package com.ldc.security.config;

import com.ldc.common.constants.ConstantsParams;
import com.ldc.security.CustomSessionInformationExpiredStrategy;
import com.ldc.security.constants.SecurityConstants;
import com.ldc.security.filter.JwtAuthorizationFilter;
import com.ldc.security.handle.*;
import com.ldc.security.service.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * @auther liudc
 * @since 2022/11/5
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    // 授权
    @Autowired
    CustomAccessDeniedHandler accessDeniedHandler;
    // 未登录
    @Autowired
    CustomAuthenticationEntryPoint authenticationEntryPoint;
    // 登录失败
    @Autowired
    CustomAuthenticationFailureHandler authenticationFailureHandler;
    // 登录成功
    @Autowired
    CustomAuthenticationSuccessHandler authenticationSuccessHandler;
    // 注销
    @Autowired
    CustomLogoutSuccessHandler logoutSuccessHandler;
    @Autowired
    CustomSessionInformationExpiredStrategy sessionInformationExpiredStrategy;
    @Autowired
    CustomUserDetailsService detailsService;

    // 加密方式
    @Bean
    public PasswordEncoder passwordEncoder() {
        // 使用BCrypt加密密码
        return new BCryptPasswordEncoder();
    }

    // Dao身份验证提供程序
    @Bean
    public DaoAuthenticationProvider daoAuthenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setPasswordEncoder(passwordEncoder());
        authenticationProvider.setUserDetailsService(detailsService);
        return authenticationProvider;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // cors()解决跨域问题，csrf()会与restful风格冲突，默认springsecurity是开启的，所以要disable()关闭一下
        http.cors().and().csrf().disable();
        // 添加过滤器
        http.addFilterBefore(new JwtAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class);
        //  其他请求需要验证
        http.authorizeRequests()
                .anyRequest()
                .authenticated();
        //
        http.formLogin()
                // post doLogin
                .loginProcessingUrl("/doLogin")
                .permitAll()
                .successHandler(authenticationSuccessHandler) // 登录成功处理
                .failureHandler(authenticationFailureHandler) // 登录失败处理
                // 账号 密码 参数
                .usernameParameter(SecurityConstants.PARAMETER_USER_NAME)
                .passwordParameter(SecurityConstants.PARAMETER_PASS_WORD)
                .and()
                .logout()//  开启注销
                .permitAll()
                .logoutSuccessHandler(logoutSuccessHandler) // 注销处理
                .deleteCookies(ConstantsParams.JSESSIONID) // 删除cookie
                .and()
                .exceptionHandling()
                .accessDeniedHandler(accessDeniedHandler) //   权限不足处理
                .authenticationEntryPoint(authenticationEntryPoint) // 未登录的处理
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .maximumSessions(1)// 最多只能一个用户登录
                .expiredSessionStrategy(sessionInformationExpiredStrategy);


    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 配置静态文件不需要认证
        web.ignoring()
                .antMatchers("/static/**");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 使用自己定义的 身份验证提供程序
        auth.authenticationProvider(daoAuthenticationProvider());
    }
}
